import axios from 'axios'
import { useRouter } from 'expo-router';
import { globalStorage } from './storage'
import { Alert } from 'react-native'
const router = useRouter()
// create an axios instance
const request = axios.create({
  baseURL: '/api'
  // withCredentials: true, // send cookies when cross-domain requests
  // headers: {
  //   'Access-Control-Allow-Origin': '*'
  // }
  // timeout: 20000 // request timeout
})

// request interceptor
request.interceptors.request.use(
  async (config) => {
    // do something before request is sent
    let token = await globalStorage.load('token')
    console.log('token:', token)
    if (token) {
      // let each request carry token
      // ['token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['token'] = token
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(
  /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

  /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
  response => {
    const res = response.data
    if (res.respCode === 401) {
      globalStorage.remove('token')
      router.push('/login')
    } else if(res.respCode!==undefined && res.respCode!==1) {
      Alert.alert("提示","您未登录或者已过期，请先登录",[
        {
          text: '确定',
          style:'default',
          onPress: () => {
            router.push('/login')
          }
        }
      ])
      return null
    }else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
   
    return Promise.reject(error)
  }
)

export default request
